import API from '@/api/auth'

const auth = {
  state: {
    userToken: null,
    roleMenu: [
      {
        name: 'home',
        icon: 'el-icon-eleme',
        title: '首页',
        children: [
          {
            name: 'layout',
            path: '/layout',
            icon: 'el-icon-s-home',
            meta: {
              title: '首页'
            }
          },
          {
            name: 'test',
            path: '/test',
            icon: 'el-icon-s-home',
            meta: {
              title: '测试页'
            }
          }
        ]
      }, {
        name: 'home',
        icon: 'el-icon-eleme',
        title: '非首页',
        children: [
          {
            name: 'layout',
            path: '/layout',
            icon: 'el-icon-s-home',
            meta: {
              title: '非首页'
            }
          },
          {
            name: 'test',
            path: '/test',
            icon: 'el-icon-s-home',
            meta: {
              title: '测试页'
            }
          }
        ]
      }
    ],
    navbar: '',
    navbarMenu: []
  },
  mutations: {
    SET_USER_TOKEN (state, userToken) {
      state.userToken = userToken
    },
    CHANGE_NAVBAR (state, navbar) {
      let obj = state.roleMenu.find(o => o.name === navbar)
      state.navbar = navbar
      state.navbarMenu = (obj && obj.children) || []
    }
  },
  actions: {
    ChangeNavBar ({ commit }, navbar) {
      commit('CHANGE_NAVBAR', navbar)
    },
    Login ({ commit }, form) {
      let userName = form.userName
      let verifyCode = form.verifyCode
      return new Promise((resolve, reject) => {
        API.UserLogin(userName, form.passWord, verifyCode).then(res => {
          if (res.code === 0) {
            const data = res.result
            commit('SET_USER_TOKEN', data)
            resolve(data)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default auth
